package com.zhanglijie.improve.atomic.two;

import java.util.concurrent.CountDownLatch;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/5 0005 22:37
 */
public class TestMyAtomicInteger {
    public static void main(String[] args) throws Exception {
          MyAtomicInteger myAtomicInteger = new MyAtomicInteger();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                myAtomicInteger.incrementAndGet();
            }
            countDownLatch.countDown();
        }).start();
        new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                myAtomicInteger.incrementAndGet();
            }
            countDownLatch.countDown();
        }).start();
        countDownLatch.await();
        System.out.println("value = "+myAtomicInteger.getValue());
        System.out.println("version = "+myAtomicInteger.getVersion());

        new Thread(()->{
            //触发ABA
            // myAtomicInteger.compareAndSet(10000,12);
            // myAtomicInteger.compareAndSet(12,10000);
            try {
                Thread.sleep(1000);
            }catch (Exception e){}
            int version = myAtomicInteger.getVersion();
            System.out.println(Thread.currentThread().getName()+"第一次版本号："+version);
            myAtomicInteger.compareAndSet(10000,12,version,version+1);
            int version2 = myAtomicInteger.getVersion();
            System.out.println(Thread.currentThread().getName()+"第二次版本号："+version2);
            myAtomicInteger.compareAndSet(12,10000,version2,version+1);
        },"thread-3").start();

        new Thread(()->{
            // try {
            //     Thread.sleep(1000);
            // }catch (Exception e){}
            // boolean b = myAtomicInteger.compareAndSet(10000, 13);
            // System.out.println("修改是否成功 "+ b);
            // System.out.println("修改后的值 "+ myAtomicInteger.getValue());
            int version = myAtomicInteger.getVersion();
            System.out.println(Thread.currentThread().getName()+"版本号："+version);
            try {
                Thread.sleep(2000);
            }catch (Exception e){}
            boolean b = myAtomicInteger.compareAndSet(10000, 13,version,version+1);
            System.out.println("修改是否成功 "+ b);
            System.out.println("修改后的值 "+ myAtomicInteger.getValue());
        },"thread-4").start();

    }
}
